import React, {FC, useCallback, useEffect, useMemo, useRef, useState} from "react";
import {Button, Col, Row, Spin} from "antd";
import {downloadFile} from "../../services/FileService.tsx";
import GlobalIcon from "../../global/GlobalIcon.tsx";

interface DocPreviewProps {
    previewKey: string,
    file: any,
    fileId: any,
    suffix: any,
    fileInfo: any,
    originUrl?: string
}

const DocPreview: FC<DocPreviewProps> = (props) => {
    const iframeRef = useRef<HTMLIFrameElement>(null);
    const [iframeUrl, setIframeUrl] = useState<string>("");

    const getUrl = useCallback(async (file: any) => {
        setIframeUrl(props.originUrl + '?src=' + encodeURIComponent(file))
    }, [props.originUrl])

    useEffect(() => {
        getUrl(props.file)
    }, [props.previewKey])

    const handlePrint = useCallback(() => {
        if (iframeRef.current && iframeRef.current.contentWindow) {
            try {
                iframeRef.current.contentWindow.print();
            } catch (error) {
                console.error("无法打印PDF:", error);
            }
        } else {
        }
    }, []);

    const handleDownload = useCallback(() => {
        downloadFile(props.fileId)
    }, [props.fileId]);

    const renderDocPreview = useMemo(() => {
        if (!iframeUrl) {
            return <Spin/>
        }
        const {fileInfo} = props;
        return <div style={{width: "100%", height: "100%", position: "relative"}}>
            <div style={{height: 30, lineHeight: "30px", textAlign: "center", position: "relative"}}>
                {fileInfo.fileName}
                <div style={{position: "absolute", top: -4, right: 25}}>
                    <Button icon={<GlobalIcon name="icon-print"/>} size="small" type="text" onClick={handlePrint}/>
                    <Button icon={<GlobalIcon name="icon-download"/>} size="small" type="text"
                            onClick={handleDownload}/>
                </div>
            </div>
            <Row justify="center" type="flex" align="middle"
                 style={{width: "100%", height: "calc(100% - 30px)", position: "absolute"}}>
                <Col><Spin size="large"/></Col>
            </Row>
            <iframe ref={iframeRef} title={'pdfpreviewtitle'} src={iframeUrl}
                    style={{width: "100%", height: "calc(100% - 30px)", border: "none", position: "absolute"}}/>
        </div>
    }, [iframeUrl, props.previewKey]);

    return (renderDocPreview);
};

export default React.memo(DocPreview);